package com.okRPC.codec;

import com.okRPC.protocol.Message;
import com.okRPC.protocol.MessageHeader;
import com.okRPC.serialization.RpcSerialization;
import com.okRPC.serialization.SerializationFactory;
import com.okRPC.serialization.SerializationTypeEnum;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Description: This is a sample class.
 * Author: Simon
 * Date: 2023/10/10
 */
public class RpcEncoder<T> extends MessageToByteEncoder<Message<T>> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message<T> message, ByteBuf byteBuf) throws Exception {

        MessageHeader header = message.getMessageHeader();

        //魔数
        byteBuf.writeShort(header.getMagic());

        //协议版本号
        byteBuf.writeByte(header.getVersion());

        //序列化算法
        byteBuf.writeByte(header.getSerialization());

        //报文类型
        byteBuf.writeByte(header.getMessageType());

        //状态
        byteBuf.writeByte(header.getMessageStatus());

        //消息id
        byteBuf.writeCharSequence(header.getRequestId(), Charset.forName("UTF-8"));

        RpcSerialization serialization = SerializationFactory.getSerialization(SerializationTypeEnum.parseByType(header.getSerialization()));

            byte[] data=serialization.serialize(message.getBody());

        byteBuf.writeInt(data.length);

        byteBuf.writeBytes(data);

    }
}
